﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iOak.Business.Campaigns;
using iOak.Domain.Resumes;
using iOak.Business.Resumes;
using iOak.Domain.Campaigns;
using iOak.Web.TemplateHelper;
using iOak.Common;
using System.Transactions;
using iOak.Common.Untity;

namespace iOak.Web.ResumeTemplates
{
    public partial class GridViewList : UserControl
    {
        private static readonly ApplicationCandidateService itemApplicationCandidateService = new ApplicationCandidateService();
        private static readonly ResumeDetailService itemResumeDetailService = new ResumeDetailService();
        private static readonly ResumeService itemResumeService = new ResumeService();
        private static readonly CampaignService itemCampaignService = new CampaignService();
        private static readonly ResumeTemplateService itemResumeTemplateService = new ResumeTemplateService();
        private static readonly PolicyService itemPolicyService = new PolicyService();
        private static readonly ApplicationService itemApplicationService = new ApplicationService();
        private static readonly ResumeFieldService itemResumeFieldService = new ResumeFieldService();
        private WorkAssistant _workassistant = new WorkAssistant();

        /// <summary>
        /// 0-企业;1-管委会
        /// </summary>
        public int PageMode
        {
            set { this.ViewState["PageMode"] = value; }
            get
            {
                int pageMode = 0;
                if (this.ViewState["PageMode"] != null)
                {
                    pageMode = int.Parse(this.ViewState["PageMode"].ToString());
                }
                return pageMode;
            }
        }

        private ApplicationBase ApplicationItem
        {
            get { return this.Session["CandidateList_ApplicationItem"] as ApplicationBase; }
            set { this.Session["CandidateList_ApplicationItem"] = value; }
        }

        private Campaign CampaignItem
        {
            get { return this.Session["CandidateList_CampaignItem"] as Campaign; }
            set { this.Session["CandidateList_CampaignItem"] = value; }
        }

        public void BindData(String argApplicationId = "", string sysKey = "")
        {
            string applicationId = String.Empty;
            if (String.IsNullOrWhiteSpace(argApplicationId))
            {
                applicationId = Convert.ToString(Session["ApplicationId"]);
            }
            else
            {
                applicationId = argApplicationId;
            }
            var list = new List<ApplicationCandidate>();
            var listTemplate = new List<ResumeField>();
            if (string.IsNullOrWhiteSpace(applicationId))
            {
                list = itemApplicationCandidateService.GetListByCompanyId(_workassistant.CurrentUser.CompanyId);
                listTemplate = itemResumeFieldService.GetDefaultFieldList();
            }
            else
            {
                list = itemApplicationCandidateService.GetListByApplicationId(new Guid(applicationId));
                var itemApplication = itemApplicationService.Retrieve(new Guid(applicationId));
                var itemCampaign = itemCampaignService.Retrieve(itemApplication.CampaignId);
                var itemPolicy = itemPolicyService.Retrieve(itemCampaign.PolicyId);
                Guid resumeTemplateId = itemPolicy.ResumeTemplateId;
                // 获取模板对象
                listTemplate = TemplateCommonHelper.GetTemplateFileList(resumeTemplateId).Where(m => m.Reqiured == true).OrderBy(m => m.ListNumber).ToList();
                ApplicationItem = itemApplication;
                CampaignItem = itemCampaign;
            }
            BindGrid(list, listTemplate, sysKey);
        }

        private void BindGrid(List<ApplicationCandidate> list, List<ResumeField> listTemplate, string sysKey)
        {
            // 动态生成GridView
            TemplateCommonHelper.SetGridViewColumn(listTemplate, gvTalentDeclareList);

            // 动态生成对象
            var nameList = listTemplate.Select(m => m.FieldName).ToList();
            nameList.Add("ResumeId");
            nameList.Add("Passed");
            nameList.Add("ApplicationCandidateId");
            Type currentType = CreateDynamicClass.CreateClass(nameList);

            // 获取当前绑定的列表Key
            var bindList = new List<dynamic>();

            // 循环添加数据
            list.ForEach(item =>
            {
                dynamic addItem = Activator.CreateInstance(currentType);
                var listResumeDetail = itemResumeDetailService.GetListByResumeId(item.ResumeId);

                if (!string.IsNullOrWhiteSpace(sysKey))
                {
                    int count = listResumeDetail.Count(m => m.ValueString.ToLower().Contains(sysKey.ToLower()));
                    if (count == 0)
                    {
                        return;
                    }
                }


                var itemResumeId = currentType.GetProperty("ResumeId");
                itemResumeId.SetValue(addItem, item.ResumeId.ToString(), null);

                var itemApplicationCandidateId = currentType.GetProperty("ApplicationCandidateId");
                itemApplicationCandidateId.SetValue(addItem, item.ApplicationCandidateId.ToString(), null);

                var itemPassed = currentType.GetProperty("Passed");
                if (item.Passed == null)
                {
                    itemPassed.SetValue(addItem, item.Passed, null);
                }
                else
                {
                    itemPassed.SetValue(addItem, Convert.ToString(item.Passed), null);
                }
                var plist = currentType.GetProperties().ToList();

                plist.ForEach(properItem =>
                {
                    var currentValue = listResumeDetail.FirstOrDefault(m => m.Key.Equals(properItem.Name));
                    if (currentValue != null)
                    {
                        properItem.SetValue(addItem, currentValue.ValueString, null);
                    }
                });

                bindList.Add(addItem);
            });

            gvTalentDeclareList.DataSource = bindList;
            gvTalentDeclareList.DataBind();

            if (PageMode == 0)
            {
                gvTalentDeclareList.Columns[gvTalentDeclareList.Columns.Count - 2].Visible = false;
            }
        }

        protected void lnkEdit_Click(object sender, EventArgs e)
        {
            Response.RedirectPermanent("ResumeEdit.aspx?ResumeId=" + hidId.Value + "&ApplicationCandidatesId=" + hidApplicationCandidatesId.Value);
            return;
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                itemResumeService.Delete(new Guid(hidId.Value));
                if (!string.IsNullOrWhiteSpace(hidApplicationCandidatesId.Value))
                {
                    itemApplicationCandidateService.Delete(new Guid(hidApplicationCandidatesId.Value));
                }
                //如果当前申请中还存在候选人，且全都通过，则改变状态
                int count = itemApplicationCandidateService.GetCount(applicationId: ApplicationItem.ApplicationId);
                if (count != 0)
                {
                    bool allPassed = itemApplicationCandidateService.AllPassed(ApplicationItem.ApplicationId);
                    if (allPassed)
                    {
                        ApplicationItem.Status = (int)ApplicationStatus.Checked;
                        itemApplicationService.Update(ApplicationItem);
                    }
                }
                ts.Complete();
            }
            BindData();
        }

        protected void gvTalentDeclareList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                dynamic item = e.Row.DataItem as dynamic;
                var lnkEdit = e.Row.FindControl("lnkEdit") as LinkButton;
                var lnkDelete = e.Row.FindControl("lnkDelete") as LinkButton;
                HyperLink hlView = e.Row.FindControl("hlView") as HyperLink;
                HyperLink hlCheck = e.Row.FindControl("hlCheck") as HyperLink;
                Label lblPassed = e.Row.FindControl("lblPassed") as Label;
                // 没有创建
                if (lnkEdit == null || lnkDelete == null)
                {
                    lnkEdit = new LinkButton();
                    lnkEdit.Text = "更新";
                    lnkDelete = new LinkButton();
                    lnkDelete.Text = "删除";
                    e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(lnkEdit);
                    e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(lnkDelete);

                    lblPassed = new Label();
                    e.Row.Cells[e.Row.Cells.Count - 2].Controls.Add(lblPassed);

                    hlView = new HyperLink();
                    hlView.Text = "查看";
                    hlCheck = new HyperLink();
                    hlCheck.Text = "审核";
                    e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(hlView);
                    e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(hlCheck);
                }
                lnkEdit.Visible = PageMode == 0;
                lnkDelete.Visible = PageMode == 0;
                hlView.Visible = PageMode == 1;
                hlCheck.Visible = PageMode == 1;
                if (PageMode == 0)
                {
                    //未通过或未审核的允许进行修改操作
                    if (string.IsNullOrEmpty(item.Passed) || !Convert.ToBoolean(item.Passed))
                    {
                        string ApplicationCandidateId = item.ApplicationCandidateId;
                        if (ApplicationCandidateId == null)
                        {
                            ApplicationCandidateId = string.Empty;
                        }
                        lnkEdit.Attributes["onclick"] = "return updateClick('" + Convert.ToString(item.ResumeId) + "','" + ApplicationCandidateId + "');";
                        lnkDelete.Attributes["onclick"] = "return deleteClick('" + Convert.ToString(item.ResumeId) + "','" + ApplicationCandidateId + "');";
                    }
                    else
                    {
                        lnkEdit.Visible = false;
                        lnkDelete.Visible = false;
                    }
                }
                else
                {
                    bool? passed = null;
                    if (!string.IsNullOrEmpty(item.Passed))
                    {
                        passed = Convert.ToBoolean(item.Passed);
                    }
                    lblPassed.Text = ResourceHelper.GetCandidateStatusName(passed);

                    String url = String.Format("/Administration/ApplicationCheck.aspx?applicationId={0}&applicationCandidateId={1}",
                                                            ApplicationItem.ApplicationId.ToString(),
                                                            item.ApplicationCandidateId.ToString());
                    hlView.NavigateUrl = url + "&viewMode=1";
                    if (ApplicationItem.Status == (int)ApplicationStatus.Submitted || ApplicationItem.Status == (int)ApplicationStatus.Checked)
                    {
                        hlCheck.NavigateUrl = url;
                    }
                    else
                    {
                        hlCheck.Visible = false;
                    }
                }
            }
        }
    }
}
